package com.writing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.writing.entity.Chapter;
import com.writing.mapper.ChapterMapper;
import com.writing.service.ChapterService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 章节服务实现类
 */
@Service
@RequiredArgsConstructor
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {
    
    @Override
    public List<Chapter> getChaptersByNovelId(Long novelId) {
        // 不返回章节内容，避免数据量过大
        return this.list(new LambdaQueryWrapper<Chapter>()
                .eq(Chapter::getNovelId, novelId)
                .select(Chapter::getId, Chapter::getNovelId, Chapter::getTitle,
                       Chapter::getSummary, Chapter::getOutline, Chapter::getNotes,
                       Chapter::getStatus, Chapter::getWordCount, Chapter::getChapterOrder,
                       Chapter::getAiGenerated, Chapter::getCreatedAt, Chapter::getUpdatedAt)
                .orderByAsc(Chapter::getChapterOrder));
    }

    @Override
    public IPage<Chapter> getChaptersByNovelIdWithPage(Long novelId, Page<Chapter> page) {
        // 不返回章节内容，避免数据量过大
        LambdaQueryWrapper<Chapter> queryWrapper = new LambdaQueryWrapper<Chapter>()
                .eq(Chapter::getNovelId, novelId)
                .select(Chapter::getId, Chapter::getNovelId, Chapter::getTitle,
                       Chapter::getSummary, Chapter::getOutline, Chapter::getNotes,Chapter::getContent,
                       Chapter::getStatus, Chapter::getWordCount, Chapter::getChapterOrder,
                       Chapter::getAiGenerated, Chapter::getCreatedAt, Chapter::getUpdatedAt)
                .orderByAsc(Chapter::getChapterOrder);

        return this.page(page, queryWrapper);
    }

    @Override
    public String getChapterContent(Long chapterId, Long novelId) {
        Chapter chapter = this.getOne(new LambdaQueryWrapper<Chapter>()
                .eq(Chapter::getId, chapterId)
                .eq(Chapter::getNovelId, novelId)
                .select(Chapter::getContent));

        return chapter != null ? chapter.getContent() : null;
    }

    @Override
    public int calculateWordCount(String content) {
        if (content == null || content.trim().isEmpty()) {
            return 0;
        }
        
        // 移除HTML标签和空白字符，计算实际字数
        String cleanContent = content.replaceAll("<[^>]*>", "")
                .replaceAll("\\s+", "");
        
        return cleanContent.length();
    }
    

    @Override
    public Chapter getChapterById(Long chapterId, Long novelId) {
        return this.getOne(new LambdaQueryWrapper<Chapter>()
                .eq(Chapter::getId, chapterId)
                .eq(Chapter::getNovelId, novelId));
    }

    @Override
    public Chapter createChapter(Chapter chapter) {
        // 设置章节顺序
        if (chapter.getChapterOrder() == null) {
            Integer maxOrder = getMaxChapterOrder(chapter.getNovelId());
            chapter.setChapterOrder(maxOrder + 1);
        }

        // 计算字数
        if (chapter.getContent() != null) {
            chapter.setWordCount(calculateWordCount(chapter.getContent()));
        }

        this.save(chapter);
        return chapter;
    }

    @Override
    public Chapter updateChapter(Chapter chapter) {
        Chapter existingChapter = getChapterById(chapter.getId(), chapter.getNovelId());
        if (existingChapter == null) {
            throw new RuntimeException("章节不存在");
        }

        // 重新计算字数
        if (chapter.getContent() != null) {
            chapter.setWordCount(calculateWordCount(chapter.getContent()));
        }

        this.updateById(chapter);
        return chapter;
    }

    @Override
    public boolean deleteChapter(Long chapterId, Long novelId) {
        Chapter chapter = getChapterById(chapterId, novelId);
        if (chapter == null) {
            throw new RuntimeException("章节不存在");
        }

        return this.removeById(chapterId);
    }

    @Override
    public void updateChapterOrder(Long novelId, List<Map<String, Object>> orderData) {
        // 解析orderData并更新章节顺序
        for (int i = 0; i < orderData.size(); i++) {
            Map<String, Object> item = orderData.get(i);
            Long chapterId = Long.valueOf(item.get("id").toString());

            Chapter chapter = new Chapter();
            chapter.setId(chapterId);
            chapter.setChapterOrder(i + 1);
            this.updateById(chapter);
        }
    }

    /**
     * 获取小说中章节的最大顺序号
     */
    private Integer getMaxChapterOrder(Long novelId) {
        List<Chapter> chapters = this.list(new LambdaQueryWrapper<Chapter>()
                .eq(Chapter::getNovelId, novelId)
                .orderByDesc(Chapter::getChapterOrder)
                .last("LIMIT 1"));

        if (chapters.isEmpty()) {
            return 0;
        }

        Integer maxOrder = chapters.get(0).getChapterOrder();
        return maxOrder != null ? maxOrder : 0;
    }
}
